package fr.curriculumvitae.anthony.stephan.fragments;

import fr.castorflex.android.flipimageview.library.FlipImageView;
import fr.castorflex.android.flipimageview.library.FlipImageView.OnFlipListener;
import fr.curriculumvitae.anthony.stephan.R;
import fr.curriculumvitae.anthony.stephan.SwipeyTabsActivity;
import fr.curriculumvitae.anthony.stephan.activities.ContactFormActivity;
import fr.curriculumvitae.anthony.stephan.activities.PwdPickerActivity;
import fr.curriculumvitae.anthony.stephan.objects.State;
import fr.curriculumvitae.anthony.stephan.slidingdrawer.SlidingDrawer;
import fr.curriculumvitae.anthony.stephan.utils.StateManager;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.SlidingDrawer.OnDrawerScrollListener;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class ContactFragment extends Fragment {
	
	private static final int REQUEST_PASSWORD = 1003;
	private static final int UNLOCKER_CALLBACK_DELAY_MS = 200; 
	private static final int ON_TOUCH_GUARD_CLICK_MS = 500;
	private static final int FLIP_ICON_CALLBACK_DELAY_MS = 5000;
	private static final int FLIP_ICON_CALLBACK_INTER_DELAY_MS = 50;
	private static final int FLIP_ICON_VELOCITY = 250;
	private static final int FLIP_ICONS_NUMBER = 6;
	
	private static Fragment INSTANCE = null;
	
	private static SwipeyTabsActivity fragmentController;
	private static Fragment mLocalContext;
	
	private final FlipImageView[] flipIcons = new FlipImageView[FLIP_ICONS_NUMBER];
	
	private Handler handler;
	private int unlockCounter;
	private FlipIconCallback flipIconCallback;
	
	private ImageView ivPhotoIcon;
	private ImageView ivResearchIcon;
	private TextView tvResearch;
	private TextView tvDisponibility;
	
	private FlipImageView ivContactGmail;
	private TextView tvContactGmail;
	private FlipImageView ivContactForm;
	private TextView tvContactForm;
	private FlipImageView ivContactLinkedIn;
	private TextView tvContactLinkedIn;
	private FlipImageView ivContactViadeo;
	private TextView tvContactViadeo;
	private FlipImageView ivContactDoyoubuzz;
	private TextView tvContactDoyoubuzz;
	
	private SlidingDrawer sdDownloadPDF;
	private ImageView ivArrowSD;
	private FlipImageView ivContactPDF;
	private TextView tvContactPDF;
	
	public static Fragment getInstance() {
		if(INSTANCE == null) {
			INSTANCE = new ContactFragment();
		} 
		return INSTANCE;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_contact, null);
		return root;
	}
	
 	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
 		fragmentController = (SwipeyTabsActivity) getActivity();
 		mLocalContext = this;
 		handler = new Handler();
 		flipIconCallback = new FlipIconCallback();
 		unlockCounter = 0;
 		fetchViews();
 		customizeViews();
 		setListeners();
 		fillFlipIcons();
 		registerCallbacks();
	}
 	
 	private void fetchViews() {
 		ivPhotoIcon = (ImageView) getView().findViewById(R.id.imageView_contact_photo_icon);
 		ivResearchIcon = (ImageView) getView().findViewById(R.id.imageView_reshearch_icon);
 		tvResearch = (TextView) getView().findViewById(R.id.textView_reshearch);
 		tvDisponibility = (TextView) getView().findViewById(R.id.textView_disponibility);
 		ivContactGmail = (FlipImageView) getView().findViewById(R.id.imageView_contact_gmail_icon);
 		tvContactGmail = (TextView) getView().findViewById(R.id.textView_contact_gmail);
 		ivContactForm = (FlipImageView) getView().findViewById(R.id.imageView_contact_form_icon);
 		tvContactForm = (TextView) getView().findViewById(R.id.textView_contact_form);
 		ivContactLinkedIn = (FlipImageView) getView().findViewById(R.id.imageView_contact_linkedin_icon);
 		tvContactLinkedIn = (TextView) getView().findViewById(R.id.textView_contact_linkedin);
 		ivContactViadeo = (FlipImageView) getView().findViewById(R.id.imageView_contact_viadeo_icon);
 		tvContactViadeo = (TextView) getView().findViewById(R.id.textView_contact_viadeo);
 		ivContactDoyoubuzz = (FlipImageView) getView().findViewById(R.id.imageView_contact_doyoubuzz_icon);
 		tvContactDoyoubuzz = (TextView) getView().findViewById(R.id.textView_contact_doyoubuzz);
 		sdDownloadPDF = (SlidingDrawer) getView().findViewById(R.id.slidingDrawer_contact_pdf);
 		ivArrowSD = (ImageView) getView().findViewById(R.id.imageView_arrow_sliding_drawer);
 		ivContactPDF = (FlipImageView) getView().findViewById(R.id.imageView_contact_pdf_icon);
 		tvContactPDF = (TextView) getView().findViewById(R.id.textView_contact_pdf);
 	}
 	
 	private void customizeViews() {
 		State state = StateManager.myState;
 		if(state != null) {
 			if(state.isVacant()) {
 				ivResearchIcon.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.ic_enabled));
 				tvResearch.setText(R.string.contact_reshearch_state_on);
 			} else {
 				ivResearchIcon.setImageDrawable(fragmentController.getResources().getDrawable(R.drawable.ic_disabled));
 				tvResearch.setText(R.string.contact_reshearch_state_off);
 			}
 			tvDisponibility.setText(state.getDisponibility());
 		}
 		sdDownloadPDF.lock();
 	}
 	
 	private void setListeners() {
 		ivPhotoIcon.setOnClickListener(onPhotoIconClickListener);
 		
 		ivContactGmail.setOnTouchListener(new OnMailClickListener(fragmentController.getResources().getString(R.string.contact_gmail_link)));
 		ivContactGmail.setOnFlipListener(new OnFlipIconListener());
 		tvContactGmail.setOnClickListener(new OnMailClickListener(fragmentController.getResources().getString(R.string.contact_gmail_link)));
 		
 		ivContactForm.setOnTouchListener(new OnFormClickListener());
 		ivContactForm.setOnFlipListener(new OnFlipIconListener());
 		tvContactForm.setOnClickListener(new OnFormClickListener());
 		
 		ivContactLinkedIn.setOnTouchListener(new OnLinkClickListener(fragmentController.getResources().getString(R.string.contact_linkedin_link)));
 		ivContactLinkedIn.setOnFlipListener(new OnFlipIconListener());
 		tvContactLinkedIn.setOnClickListener(new OnLinkClickListener(fragmentController.getResources().getString(R.string.contact_linkedin_link)));
 		
 		ivContactViadeo.setOnTouchListener(new OnLinkClickListener(fragmentController.getResources().getString(R.string.contact_viadeo_link)));
 		ivContactViadeo.setOnFlipListener(new OnFlipIconListener());
 		tvContactViadeo.setOnClickListener(new OnLinkClickListener(fragmentController.getResources().getString(R.string.contact_viadeo_link)));
 		
 		ivContactDoyoubuzz.setOnTouchListener(new OnLinkClickListener(fragmentController.getResources().getString(R.string.contact_doyoubuzz_link)));
 		ivContactDoyoubuzz.setOnFlipListener(new OnFlipIconListener());
 		tvContactDoyoubuzz.setOnClickListener(new OnLinkClickListener(fragmentController.getResources().getString(R.string.contact_doyoubuzz_link)));
 		
 		sdDownloadPDF.setOnDrawerScrollListener(onDrawerScrollListener);
 		ivArrowSD.setOnClickListener(onOpenDrawerClickListener);
 		ivContactPDF.setOnTouchListener(new OnDownloadClickListener());
 		ivContactPDF.setOnFlipListener(new OnFlipIconListener());
 		tvContactPDF.setOnClickListener(new OnDownloadClickListener());
 	}
 	
 	private void fillFlipIcons() {
 		flipIcons[0] = ivContactPDF;
 		flipIcons[1] = ivContactDoyoubuzz;
 		flipIcons[2] = ivContactViadeo;
 		flipIcons[3] = ivContactLinkedIn;
 		flipIcons[4] = ivContactForm;
 		flipIcons[5] = ivContactGmail;
 	}
 	
 	private void registerCallbacks() {
 		handler.postDelayed(flipIconCallback, FLIP_ICON_CALLBACK_DELAY_MS);
 	}
 	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {  
    	super.onActivityResult(requestCode, resultCode, data);
    	if(requestCode == REQUEST_PASSWORD) {
			if(SwipeyTabsActivity.mToast!=null){
				SwipeyTabsActivity.mToast.cancel();
			}
    		if(resultCode == Activity.RESULT_OK) {
				SwipeyTabsActivity.enableAdminMenu();
				unlockCounter = Integer.MIN_VALUE;
				SwipeyTabsActivity.mToast = Toast.makeText(fragmentController, fragmentController.getResources().getString(R.string.pwd_picker_unlocked), Toast.LENGTH_LONG);
				SwipeyTabsActivity.mToast.show();
    		} else if(resultCode == Activity.RESULT_FIRST_USER) {
    			SwipeyTabsActivity.mToast = Toast.makeText(fragmentController, fragmentController.getResources().getString(R.string.pwd_picker_failed), Toast.LENGTH_LONG);
    			SwipeyTabsActivity.mToast.show();
    		}
    	}
    }
    
 	
 	  ///////////////
 	 // LISTENERS //
 	///////////////
    
 	private OnClickListener onPhotoIconClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			handler.removeCallbacks(unlockerCallback);
			unlockCounter++;
			if(unlockCounter == 7) {
				Intent i = new Intent(fragmentController, PwdPickerActivity.class);
				mLocalContext.startActivityForResult(i, REQUEST_PASSWORD);
			} else {
				handler.postDelayed(unlockerCallback, UNLOCKER_CALLBACK_DELAY_MS);
			}
		}
 	};
 	
 	
 	private class OnFlipIconListener implements OnFlipListener {
		@Override
		public void onClick(FlipImageView view) {
			view.setInterpolator(new AccelerateDecelerateInterpolator());
			view.setDuration(FLIP_ICON_VELOCITY);
	        view.setRotationXEnabled(false);
	        view.setRotationYEnabled(true);
	        view.setRotationZEnabled(false);
	        view.setRotationReversed(false);
		}
		@Override public void onFlipStart(FlipImageView view) { /* nothing to do */ }
		@Override public void onFlipEnd(FlipImageView view) 	{ /* nothing to do */ }
 	};
 	
 	
 	private class OnMailClickListener implements OnClickListener, OnTouchListener {
 		private final String mail;
 		public OnMailClickListener(String mail) {
 			this.mail = mail;
 		}
		@Override
		public void onClick(View v) {
			Intent mailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", mail, null));
			mailIntent.putExtra(Intent.EXTRA_SUBJECT, fragmentController.getResources().getString(R.string.contact_mail_default_subject));
			startActivity(Intent.createChooser(mailIntent, fragmentController.getResources().getString(R.string.contact_by_email)));
		}
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			v.setOnTouchListener(null);
			Intent mailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", mail, null));
			mailIntent.putExtra(Intent.EXTRA_SUBJECT, fragmentController.getResources().getString(R.string.contact_mail_default_subject));
			startActivity(Intent.createChooser(mailIntent, fragmentController.getResources().getString(R.string.contact_by_email)));
			handler.postDelayed(new ResetTouchCallback(v, this), ON_TOUCH_GUARD_CLICK_MS);
			return false;
		}
 	};
 	
 	
 	private class OnLinkClickListener implements OnClickListener, OnTouchListener {
 		private final String link;
 		public OnLinkClickListener(String link) {
 			this.link = link;
 		}
		@Override
		public void onClick(View v) {
			Intent startIntent = new Intent(Intent.ACTION_VIEW);
			startIntent.setData(Uri.parse(link));
			startActivity(startIntent);
		}
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			v.setOnTouchListener(null);
			Intent startIntent = new Intent(Intent.ACTION_VIEW);
			startIntent.setData(Uri.parse(link));
			startActivity(startIntent);
			handler.postDelayed(new ResetTouchCallback(v, this), ON_TOUCH_GUARD_CLICK_MS);
			return false;
		}
 	};
 	
 	
 	private class OnFormClickListener implements OnClickListener, OnTouchListener {
		@Override
		public void onClick(View v) {
			Intent startIntent = new Intent(fragmentController, ContactFormActivity.class);
			startActivity(startIntent);
		}
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			v.setOnTouchListener(null);
			Intent startIntent = new Intent(fragmentController, ContactFormActivity.class);
			startActivity(startIntent);
			handler.postDelayed(new ResetTouchCallback(v, this), ON_TOUCH_GUARD_CLICK_MS);
			return false;
		}
 	};
 	
 	
 	private class OnDownloadClickListener implements OnClickListener, OnTouchListener {
		@Override
		public void onClick(View v) {
			fragmentController.downloadPdfCV();
		}
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			v.setOnTouchListener(null);
			fragmentController.downloadPdfCV();
			handler.postDelayed(new ResetTouchCallback(v, this), ON_TOUCH_GUARD_CLICK_MS);
			return false;
		}
 	};
 	
 	
 	private OnClickListener onOpenDrawerClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if(sdDownloadPDF.isOpened()) {
				sdDownloadPDF.animateClose();
			} else {
				sdDownloadPDF.animateOpen();
			}
		}
 	};
 	
 	
 	private OnDrawerScrollListener onDrawerScrollListener = new OnDrawerScrollListener() {
		@Override
		public void onScrollStarted() {
			RotateAnimation anim;
			if(!sdDownloadPDF.isOpened()) {
				anim = (RotateAnimation) AnimationUtils.loadAnimation(fragmentController, R.anim.rotate_icon_clockwise);

			} else {
				anim = (RotateAnimation) AnimationUtils.loadAnimation(fragmentController, R.anim.rotate_icon_trigo);
			}
			anim.setInterpolator(new LinearInterpolator());
			anim.setFillAfter(true);
			ivArrowSD.startAnimation(anim);
		}
		@Override
		public void onScrollEnded() {
			/* nothing to do */
			if(!sdDownloadPDF.isOpened()) {
		 		ivContactDoyoubuzz.bringToFront();
		 		tvContactDoyoubuzz.bringToFront();
			}
		}
 	};
 	
 	
	  ///////////////
	 // CALLBACKS //
	///////////////
 	
 	private class FlipIconCallback implements Runnable {
 		private int current = 0;
 		private int max = FLIP_ICONS_NUMBER;
 		@Override 
 		public void run() {
 			handler.removeCallbacks(flipIconCallback);
 			flipIcons[current].performClick();
 			current++;
 			if(current >= max) {
 				current = 0;
 				handler.postDelayed(flipIconCallback, FLIP_ICON_CALLBACK_DELAY_MS);
 			} else {
 				handler.postDelayed(flipIconCallback, FLIP_ICON_CALLBACK_INTER_DELAY_MS);
 			}
 		}
 	};
 	
 	private class ResetTouchCallback implements Runnable {
 		private View view;
 		private OnTouchListener listener;
 		public ResetTouchCallback(View view, OnTouchListener listener) {
 			this.view = view;
 			this.listener = listener;
 		}
		@Override
		public void run() {
			view.setOnTouchListener(listener);
		}
 	}
 	
 	private Runnable unlockerCallback = new Runnable() {
		@Override
		public void run() {
			handler.removeCallbacks(unlockerCallback);
			unlockCounter = 0;
		}
 	};
 	
}
